package com.jiangyao.common.utils;

import org.nustaq.serialization.FSTConfiguration;

/**
 * 序列化工具
 *
 * @author: yangyongchuan
 * @create: 2020年05月05日 16:22
 */
public final class SerializeUtil {
	private static final ThreadLocal<FSTConfiguration> confLocals = new ThreadLocal<>();

	private static FSTConfiguration conf() {
		FSTConfiguration conf = confLocals.get();
		if (conf == null) {
			conf = FSTConfiguration.createDefaultConfiguration();
			confLocals.set(conf);
		}
		return conf;
	}

	private SerializeUtil() {

	}

	/**
	 * 序列化
	 *
	 * @param object 序列对象
	 * @return 结果
	 */
	public static byte[] serialize(Object object) {
		if (object == null) {
			return null;
		}
		return conf().asByteArray(object);
	}

	/**
	 * 反序列化
	 *
	 * @param bytes 反序列字节
	 * @return 对象
	 */
	@SuppressWarnings("unchecked")
	public static <T> T unserialize(byte[] bytes) {
		if (bytes == null || bytes.length == 0) {
			return null;
		}
		return (T) conf().asObject(bytes);
	}



}
